package com.cloud.admin.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloud.admin.common.constant.UserConstants;
import com.cloud.admin.common.core.domain.AjaxResult;
import com.cloud.admin.common.core.page.TableDataInfo;
import com.cloud.admin.model.entity.SysRole;
import com.cloud.admin.model.entity.SysUser;
import com.cloud.admin.model.entity.SysUserRole;
import com.cloud.admin.service.SysRoleService;
import com.cloud.admin.service.SysUserService;
import com.cloud.admin.shiro.security.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

/**
 * 角色信息
 *
 * @author douhaichao
 */
@Controller
@RequestMapping("/system/role")
public class SysRoleController extends BaseController {
    private String prefix = "system/role";

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysUserService userService;

    @RequiresPermissions("system:role:view")
    @GetMapping()
    public ModelAndView role() {
        ModelAndView view = super.baseView("role", prefix + "/role");
        return view;
    }

    @RequiresPermissions("system:role:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysRole role, Page page) {
        role.setDelFlag("0");
        IPage<SysRole> iPage = roleService.selectPageByLike(page, role);
        return getDataTable(iPage);
    }

    /**
     * 新增用户
     */
    @GetMapping("add")
    public ModelAndView add() {
        ModelAndView view = super.baseView("add", prefix + "/add");
        return view;
    }

    /**
     * 新增保存角色
     */
    @RequiresPermissions("system:role:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysRole role) {
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return error("新增角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setCreateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(roleService.insertRole(role));

    }

    /**
     * 修改用户
     */
    @GetMapping("edit/{roleId}")
    public ModelAndView edit(@PathVariable("roleId") Long roleId) {
        ModelAndView view = super.baseView("edit", prefix + "/edit");
        SysRole sysRole = new SysRole();
        sysRole.setRoleId(roleId.intValue());
        view.addObject("role", roleService.selectOne(sysRole));
        return view;
    }

    /**
     * 修改保存角色
     */
    @RequiresPermissions("system:role:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysRole role) {
        if (UserConstants.ROLE_NAME_NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) {
            return error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        } else if (UserConstants.ROLE_KEY_NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) {
            return error("修改角色'" + role.getRoleName() + "'失败，角色权限已存在");
        }
        role.setUpdateBy(ShiroUtils.getLoginName());
        ShiroUtils.clearCachedAuthorizationInfo();
        return toAjax(roleService.updateRole(role));
    }

    /**
     * 角色分配数据权限
     */
    @GetMapping("/authDataScope/{roleId}")
    public ModelAndView authDataScope(@PathVariable("roleId") Long roleId) {
        ModelAndView view = super.baseView("authDataScope", prefix + "/dataScope");
        SysRole sysRole = new SysRole();
        sysRole.setDelFlag("0");
        sysRole.setRoleId(roleId.intValue());
        view.addObject("role", roleService.selectOne(sysRole));
        return view;
    }

    /**
     * 保存角色分配数据权限
     */
    @RequiresPermissions("system:role:edit")
    @PostMapping("/authDataScope")
    @ResponseBody
    public AjaxResult authDataScopeSave(SysRole role) {
        role.setUpdateBy(ShiroUtils.getLoginName());
        if (roleService.authDataScope(role) > 0) {
            /// 这里需要把SysUser对象转成User
//            ShiroUtils.setSysUser(
//                    userService.selectUserById(ShiroUtils.getSysUser().getUserId()));
            return success();
        }
        return error();
    }

    @RequiresPermissions("system:role:remove")
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(roleService.deleteRoleByIds(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 校验角色名称
     */
    @PostMapping("/checkRoleNameUnique")
    @ResponseBody
    public String checkRoleNameUnique(SysRole role) {
        role.setDelFlag("0");
        return roleService.checkRoleNameUnique(role);
    }

    /**
     * 校验角色权限
     */
    @PostMapping("/checkRoleKeyUnique")
    @ResponseBody
    public String checkRoleKeyUnique(SysRole role) {
        return roleService.checkRoleKeyUnique(role);
    }

    /**
     * 选择菜单树
     */
    @GetMapping("/selectMenuTree")
    public ModelAndView selectMenuTree() {
        ModelAndView view = super.baseView("selectMenuTree", prefix + "/tree");
        return view;
    }

    /**
     * 角色状态修改
     */
    @RequiresPermissions("system:role:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysRole role) {
        return toAjax(roleService.changeStatus(role));
    }

    /**
     * 分配用户
     */
    @RequiresPermissions("system:role:edit")
    @GetMapping("/authUser/{roleId}")
    public ModelAndView authUser(@PathVariable("roleId") Long roleId) {
        ModelAndView view = super.baseView("authUser", prefix + "/authUser");
        SysRole sysRole = new SysRole();
        sysRole.setDelFlag("0");
        sysRole.setRoleId(roleId.intValue());
        view.addObject("role", roleService.selectOne(sysRole));
        return view;
    }

    /**
     * 查询已分配用户角色列表
     */
    @RequiresPermissions("system:role:list")
    @PostMapping("/authUser/allocatedList")
    @ResponseBody
    public TableDataInfo allocatedList(SysUser user, Page page) {
        IPage<SysUser> sysUserIPage = userService.selectAllocatedList(page, user);
        return getDataTable(sysUserIPage);
    }

    /**
     * 取消授权
     */
    @PostMapping("/authUser/cancel")
    @ResponseBody
    public AjaxResult cancelAuthUser(SysUserRole userRole) {
        return toAjax(roleService.deleteAuthUser(userRole));
    }

    /**
     * 批量取消授权
     */
    @PostMapping("/authUser/cancelAll")
    @ResponseBody
    public AjaxResult cancelAuthUserAll(Long roleId, String userIds) {
        return toAjax(roleService.deleteAuthUsers(roleId, userIds));
    }

    /**
     * 选择用户
     */
    @GetMapping("/authUser/selectUser/{roleId}")
    public ModelAndView selectUser(@PathVariable("roleId") Long roleId) {
        ModelAndView view = super.baseView("selectUser", prefix + "/selectUser");
        SysRole sysRole = new SysRole();
        sysRole.setDelFlag("0");
        sysRole.setRoleId(roleId.intValue());
        view.addObject("role", roleService.selectOne(sysRole));
        return view;

    }

    /**
     * 查询未分配用户角色列表
     */
    @RequiresPermissions("system:role:list")
    @PostMapping("/authUser/unallocatedList")
    @ResponseBody
    public TableDataInfo unallocatedList(SysUser user, Page page) {
        IPage<SysUser> sysUserIPage = userService.selectUnallocatedList(page, user);
        return getDataTable(sysUserIPage);
    }

    /**
     * 批量选择用户授权
     */
    @PostMapping("/authUser/selectAll")
    @ResponseBody
    public AjaxResult selectAuthUserAll(Long roleId, String userIds) {
        return toAjax(roleService.insertAuthUsers(roleId, userIds));
    }
}